package com.feeyo.groundservice.wifi.util

import android.annotation.SuppressLint
import android.content.Context
import android.net.wifi.WifiManager
import android.util.Log
import com.feeyo.android.util.FyLog
import com.feeyo.android.util.toJson
import java.lang.reflect.InvocationTargetException
import java.net.NetworkInterface
import java.net.SocketException

/**
 *作者：70893 on 2024-11-11
 *描述：
 */
internal object APUtil {

    private val TAG = javaClass.simpleName
    fun getWifiApIpAddress(): String? {

        try {
            val en = NetworkInterface.getNetworkInterfaces()
            while (en.hasMoreElements()) {
                val intf = en.nextElement()
                if (intf.name.contains("wlan")) {
                    val enumIpAddr = intf.inetAddresses
                    while (enumIpAddr.hasMoreElements()) {
                        val inetAddress = enumIpAddr.nextElement()
                        if (!inetAddress.isLoopbackAddress && (inetAddress.address.size == 4)) {
                            inetAddress.hostAddress?.let { Log.d(TAG, it) }
                            return inetAddress.hostAddress
                        }
                    }
                }
            }

        } catch (e: SocketException) {
            FyLog.e(TAG, e.toJson())
        }

        return null
    }

    /**热点是否开启 */
    @SuppressLint("PrivateApi")
    fun isWifiApOpen(context: Context): Boolean {
        try {
            val manager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
            //通过放射获取 getWifiApState()方法
            val method = manager.javaClass.getDeclaredMethod("getWifiApState")
            //调用getWifiApState() ，获取返回值
            val state = method.invoke(manager) as Int
            //通过放射获取 WIFI_AP的开启状态属性
            val field = manager.javaClass.getDeclaredField("WIFI_AP_STATE_ENABLED")
            //获取属性值
            val value = field[manager] as Int
            //判断是否开启
            return state == value
        } catch (e: NoSuchMethodException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        }
        return false
    }

}